What is stripe?
The Stripe npm package is a library that provides a powerful and easy-to-use interface to the Stripe API, allowing developers to integrate payment processing into their Node.js applications. It supports a wide range of payment operations, from charging credit cards to managing subscriptions and handling disputes.
What are stripe's main functionalities?
Charging a Credit Card
This feature allows you to create a charge on a credit card. The amount is specified in the smallest currency unit (e.g., cents for USD).
stripe.charges.create({
amount: 2000,
currency: 'usd',
source: 'tok_amex',
description: 'Charge for jenny.rosen@example.com'
}).then(function(charge) {
// asynchronously called
});
Creating a Customer
This feature enables you to create a new customer object, which can be used for recurring charges and tracking multiple charges that are associated with the same customer.
stripe.customers.create({
email: 'customer@example.com'
}).then(function(customer) {
// asynchronously called
});
Managing Subscriptions
This feature allows you to create and manage subscriptions for recurring payments. You can specify the plan and customer to associate with the subscription.
stripe.subscriptions.create({
customer: 'cus_4fdAW5ftNQow1a',
items: [{
plan: 'plan_CBXbz9i7AIOTzr'
}]
}).then(function(subscription) {
// asynchronously called
});
Handling Webhooks
This feature is for setting up a webhook endpoint to listen for events from Stripe. This is useful for receiving notifications about various events, such as successful payments or subscription cancellations.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.post('/webhook', bodyParser.raw({type: 'application/json'}), (request, response) => {
let event;
try {
event = JSON.parse(request.body);
} catch (err) {
response.status(400).send(`Webhook Error: ${err.message}`);
return;
}
// Handle the event
switch (event.type) {
case 'payment_intent.succeeded':
const paymentIntent = event.data.object;
console.log(`PaymentIntent was successful!`);
break;
// ... handle other event types
default:
console.log(`Unhandled event type ${event.type}`);
}
response.status(200).end();
});
app.listen(8000, () => {
console.log('Running on port 8000');
});
Other packages similar to stripe
braintree
Braintree is a full-stack payment platform that makes it easy to accept payments in your app or website. It offers similar functionalities to Stripe, including payment processing, subscription management, and fraud protection. Braintree is known for its PayPal integration, which can be a deciding factor for some businesses.
square-connect
Square Connect is the official Square npm package. It provides access to various Square services, including payment processing. While it offers similar features to Stripe, such as handling transactions and managing customers, it is particularly tailored for businesses that use Square's point of sale system.
mollie-api-node
Mollie is a payment service provider that offers an easy-to-implement process for integrating payments into a website or app. It supports various payment methods and is known for its simplicity. However, it might not have as extensive a feature set as Stripe, particularly in terms of global reach and customization options.
Stripe Node.js Library
The Stripe Node library provides convenient access to the Stripe API from
applications written in server-side JavaScript.
Please keep in mind that this package is for use with server-side Node that
uses Stripe secret keys. To maintain PCI compliance, tokenization of credit
card information should always be done with Stripe.js on the
client side. This package should not be used for that purpose.
Documentation
See the Node API docs.
Installation
Install the package with:
npm install stripe --save
Usage
The package needs to be configured with your account's secret key which is
available in your Stripe Dashboard. Require it with the key's
value:
var stripe = require('stripe')('sk_test_...');
stripe.customers.create(
{ email: 'customer@example.com' },
function(err, customer) {
err;
customer;
}
);
On ES6, this looks more like:
import stripePackage from 'stripe';
const stripe = stripePackage('sk_test_...');
Using Promises
Every method returns a chainable promise which can be used instead of a regular
callback:
stripe.customers.create({
email: 'foo-customer@example.com'
}).then(function(customer){
return stripe.customers.createSource(customer.id, {
source: {
object: 'card',
exp_month: 10,
exp_year: 2018,
number: '4242 4242 4242 4242',
cvc: 100
}
});
}).then(function(source) {
return stripe.charges.create({
amount: 1600,
currency: 'usd',
customer: source.customer
});
}).then(function(charge) {
}).catch(function(err) {
});
Configuring Timeout
Request timeout is configurable (the default is Node's default of 120 seconds):
stripe.setTimeout(20000);
Configuring For Connect
A per-request Stripe-Account
header for use with Stripe Connect
can be added to any method:
stripe.balance.retrieve({
stripe_account: 'acct_foo'
}).then(function(balance) {
}).catch(function(err) {
});
Configuring a Proxy
An https-proxy-agent can be configured with
setHttpAgent
.
To use stripe behind a proxy you can pass to sdk:
if (process.env.http_proxy) {
const ProxyAgent = require('https-proxy-agent');
stripe.setHttpAgent(new ProxyAgent(process.env.http_proxy));
}
Examining Responses
Some information about the response which generated a resource is available
with the lastResponse
property:
charge.lastResponse.requestId
charge.lastResponse.statusCode
request
and response
events
The Stripe object emits request
and response
events. You can use them like this:
var stripe = require('stripe')('sk_test_...');
function onRequest(request) {
}
stripe.on('request', onRequest);
stripe.off('request', onRequest);
request
object
{
api_version: 'latest',
account: 'acct_TEST',
idempotency_key: 'abc123',
method: 'POST',
path: '/v1/charges'
}
response
object
{
api_version: 'latest',
account: 'acct_TEST',
idempotency_key: 'abc123',
method: 'POST',
path: '/v1/charges',
status: 402,
request_id: 'req_Ghc9r26ts73DRf',
elapsed: 445
}
Webhook signing
Stripe can optionally sign the webhook events it sends to your endpoint, allowing you to validate that they were not sent by a third-party. You can read more about it here.
You can find an example of how to use this with Express in the examples/webhook-signing
folder, but here's what it looks like:
event = stripe.webhooks.constructEvent(
webhookRawBody,
webhookStripeSignatureHeader,
webhookSecret
);
Writing a Plugin
If you're writing a plugin that uses the library, we'd appreciate it if you identified using stripe.setAppInfo()
:
stripe.setAppInfo({
name: 'MyAwesomePlugin',
version: '1.2.34',
url: 'https://myawesomeplugin.info',
});
This information is passed along when the library makes calls to the Stripe API.
More Information
Development
Run all tests:
$ npm install
$ npm test
Run a single test suite:
$ npm run mocha -- test/Error.spec.js
Run a single test (case sensitive):
$ npm run mocha -- test/Error.spec.js --grep 'Populates with type'
If you wish, you may run tests using your Stripe Test API key by setting the
environment variable STRIPE_TEST_API_KEY
before running the tests:
$ export STRIPE_TEST_API_KEY='sk_test....'
$ npm test